package com.topc.problem.util;

import com.topc.base.exception.Asserts;
import com.topc.problem.model.po.ProblemSample;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FileToSamplesUtils {

    public static List<ProblemSample> getProblemSampleByFile(MultipartFile[] files){
        if (files.length==0||files.length%2==1) Asserts.fail("请文件列表不能为空或者文件数出错");
        List<String> sampleString = new ArrayList<>();
        for (int i = 0;i<files.length;i++){
            try {
                if (!files[i].getOriginalFilename().endsWith(".txt")) Asserts.fail("文件格式有误，应为txt");
                String fileContent = new String(files[i].getInputStream().readAllBytes(), StandardCharsets.UTF_8);
                sampleString.add(fileContent);
            } catch (IOException e) {
                Asserts.fail("文件出错");
            }
        }
        List<ProblemSample> samples = new ArrayList<>();
        for (int i = 0; i < sampleString.size(); i++) {
            ProblemSample problemSample = new ProblemSample();
            problemSample.setInput(sampleString.get(i)).setOutput(sampleString.get(++i));
            samples.add(problemSample);
        }
        return samples;
    }
}
